package com.tiantianyuegou.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.LocalStoreAdapter;
import com.tiantianyuegou.adapter.ScreenStoreAdapter;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.LocalStoreInfo;
import com.tiantianyuegou.model.ScreenStoreModel;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.NetworkUtils;
import com.tiantianyuegou.util.Tools;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 店铺列表
 * 店家详情
 * Created by huyang on 2016/1/13 0013.
 */
public class StoreListActivity extends BaseActivity implements View.OnClickListener {

    private TextView tv_servicebag, tv_area, tv_storelevel, tv_time;
    private ImageView iv_servicebag, iv_area, iv_storelevel, iv_time;
    private LinearLayout layou_servicebag, layout_area, layout_storelevel, layout_time;
    private FrameLayout layout_no_store;
    private boolean isSelect = true;
    private PopupWindow popupWindow;
    private ListView listView;
    private PullToRefreshListView refreshListView;
    private LocalStoreAdapter storeAdapter;
    private ScreenStoreAdapter mAdapter;
    private String text;
    private int mPosition;
    private String label;//记录上次选中的分类
    private String area;//记录上次选中的区域
    private String level;//记录上次选中的店铺等级
    private String time;//记录上次选中的时间
    private String mLevel = "";//店铺等级默认排序
    private String mTime = "";//店铺时间默认排序
    private String tsId;//店铺id
    private String tcName;//店铺名称
    private String TAG = "StoreListActivity";
    private String tcId;//分类id
    private String areaID;//区域ID
    private int mPage = 0;
    private boolean isRefresh = true;
    private boolean isLoadMore = false;
    //    private TextView tv_label;
//    private ImageView iv_gou;
    private LoadingDialog loadingDialog;
    private List<ScreenStoreModel> data;
    private List<ScreenStoreModel> areaData;
    private List<ScreenStoreModel> storelvData;
    private List<ScreenStoreModel> timeData;
    private List<LocalStoreInfo> datas;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_storelist);
        initViews();
        getData();
        setTitle(label);
        Tools.changeSystemBar(this);
//        loadStoreData(tcId, areaID);
    }

    @Override
    public void findViewByIds() {
      /*  tv_servicebag = (TextView) findViewById(R.id.tv_servicebag);
        tv_area = (TextView) findViewById(R.id.tv_area);
        tv_storelevel = (TextView) findViewById(R.id.tv_storelevel);
        tv_time = (TextView) findViewById(R.id.tv_time);
        iv_servicebag = (ImageView) findViewById(R.id.iv_servicebag);
        iv_area = (ImageView) findViewById(R.id.iv_area);
        iv_storelevel = (ImageView) findViewById(R.id.iv_storelevel);
        iv_time = (ImageView) findViewById(R.id.iv_time);
        layou_servicebag = (LinearLayout) findViewById(R.id.layout_servicebag);
        layout_area = (LinearLayout) findViewById(R.id.layout_area);
        layout_storelevel = (LinearLayout) findViewById(R.id.layout_storelevel);
        layout_time = (LinearLayout) findViewById(R.id.layout_time);
        refreshListView = (PullToRefreshListView) findViewById(R.id.listview_select);
        layout_no_store = (FrameLayout) findViewById(R.id.layout_no_store);
        layout_no_store.setVisibility(View.GONE);
*/
     /*   //下拉刷新
        ILoadingLayout pullDownRefresh = refreshListView.getLoadingLayoutProxy(true, false);
        pullDownRefresh.setPullLabel("下拉刷新");//下拉提示
        pullDownRefresh.setRefreshingLabel("正在刷新...");//刷新提示
        pullDownRefresh.setReleaseLabel("松开刷新");//下拉一定距离显示的提示
        //上拉加载
        ILoadingLayout pullUpRefresh = refreshListView.getLoadingLayoutProxy(false, true);
        pullUpRefresh.setPullLabel("上拉加载");
        pullUpRefresh.setRefreshingLabel("正在刷新...");
        pullUpRefresh.setReleaseLabel("松开加载更多");
*/

    }

    @Override
    public void initListener() {
      /*  datas = new ArrayList<>();
        data = new ArrayList<>();
        storelvData = new ArrayList<>();
        timeData = new ArrayList<>();
        areaData = new ArrayList<>();
        storeAdapter = new LocalStoreAdapter(this);
        mAdapter = new ScreenStoreAdapter(this);
        refreshListView.setAdapter(storeAdapter);
        loadingDialog = new LoadingDialog(this);
        layou_servicebag.setOnClickListener(this);
        layout_area.setOnClickListener(this);
        layout_storelevel.setOnClickListener(this);
        layout_time.setOnClickListener(this);
        refreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(StoreListActivity.this, StoreDetailActivity.class);
                String tsId = datas.get(i-1).getTsId();
                intent.putExtra("tsId", tsId);
                Log.v(TAG,"-----------tsid="+tsId);
                startActivity(intent);
            }
        });
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //下拉刷新
                mPage = 0;
                loadStoreData(tcId, areaID);
                isRefresh = true;
                isLoadMore = false;
                String label = DateUtils.formatDateTime(
                        getApplicationContext(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                refreshListView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                //上拉加载
                loadStoreData(tcId, areaID);
                isRefresh = false;
                isLoadMore = true;
                String label = DateUtils.formatDateTime(
                        getApplicationContext(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                refreshListView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
            }
        });*/
    }

    public void getData() {
      /*  Intent intent = getIntent();
        tcName = intent.getStringExtra("tcName");
        label = tcName;
        tv_servicebag.setText(tcName);
        tcId = intent.getStringExtra("tcId");
        Log.e(TAG, "-------tcname=" + tcName);

        //storelvData.clear();
        ScreenStoreModel desc = new ScreenStoreModel();
        desc.setLabel("从高到低");
        ScreenStoreModel asc = new ScreenStoreModel();
        asc.setLabel("从低到高");
        storelvData.add(desc);
        storelvData.add(asc);
        desc.setIsSelect(false);
        asc.setIsSelect(false);
        //                TODO 需换成真是字段名成
//        mAdapter.setData(storelvData);
        mAdapter.notifyDataSetChanged();

        //   timeData.clear();
        ScreenStoreModel newest = new ScreenStoreModel();
        newest.setLabel("新店开张");
        ScreenStoreModel old = new ScreenStoreModel();
        old.setLabel("精品老店");
        timeData.add(newest);
        timeData.add(old);
        newest.setIsSelect(false);
        old.setIsSelect(false);
        //                TODO 需换成真是字段名成
//        mAdapter.setData(timeData);
        mAdapter.notifyDataSetChanged();*/
    }

    //加载商铺列表
 /*   public void loadStoreData(String tcId, String areaID) {

        if (!NetworkUtils.isNetworkAvailable(this)) {
            showMsg("请检查网络");
        }
        mPage=0;
        datas.clear();

        loadingDialog.showDialog();
        loadingDialog.setMsg("正在加载");
        RequestParams params = new RequestParams();
        params.addBodyParameter("tcId", tcId);
        params.addBodyParameter("page", (++mPage) + "");
        Log.e(TAG,"    mPage:"+mPage);
        params.addBodyParameter("cityId", SPHelper.getCityId());
        if (areaID != null && !"".equals(areaID)) {
            params.addBodyParameter("countyId", areaID);
            Log.v(TAG, "---------countyID=" + areaID);
        }
        System.out.println("------------cityId=" + SPHelper.getCityId());
        params.addBodyParameter("grade", mLevel);
        params.addBodyParameter("time", mTime);
        System.out.println("-------mLevel=" + mLevel + "----------mTime=" + mTime);
        Log.e(TAG, "----+++++----tcid=" + tcId);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.STORE_LIST, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                loadingDialog.dismiss();
                refreshListView.onRefreshComplete();
                Log.e(TAG, "onSuccess response.result" +
                        response.result);
                if (TextUtils.isEmpty(response.result)) {
                    showMsg("获取商家列表失败");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            layout_no_store.setVisibility(View.GONE);
                            JSONArray list = jsonObject.getJSONArray("list");
                            if (isRefresh) {
                                datas.clear();
                                isRefresh = false;
                            } else if (isLoadMore) {
                                isLoadMore = false;
                            }
                            for (int i = 0; i < list.length(); i++) {
                                JSONObject temp = list.getJSONObject(i);
                                tsId = temp.getString("tsId");
                                String tsName = temp.getString("tsName");
                                String province = temp.getString("province");
                                String city = temp.getString("city");
                                String county = temp.getString("county");
                                String tsLogo = temp.getString("tsLogo");
                                int tsIntegral = temp.getInt("tsIntegral");

                                LocalStoreInfo info = new LocalStoreInfo();
                                info.setTsId(tsId);
                                info.setStoreName(tsName);
                                info.setProvince(province);
                                info.setCity(city);
                                info.setArea(county);
                                info.setTsLogo(tsLogo);
                                info.setTsIntegral(tsIntegral);
                                datas.add(info);
                            }
                            if (datas.size() == 0) {
                                layout_no_store.setVisibility(View.VISIBLE);
                            }
                            storeAdapter.setData(datas);
                            storeAdapter.notifyDataSetChanged();
                        } else if (code.equalsIgnoreCase("103")) {
                            if (!isLoadMore) {
                                showMsg("暂无店铺");
                                layout_no_store.setVisibility(View.VISIBLE);
                                datas.clear();
                                storeAdapter.setData(datas);
                                storeAdapter.notifyDataSetChanged();
                            }
                            if (isLoadMore&&datas.size()>0){
                                isLoadMore = false;
                                mPage--;
                                showMsg("没有更多店铺了");
                            }else{
                                layout_no_store.setVisibility(View.VISIBLE);
//                                showMsg("暂无店铺");
                            }
                        }
                    } catch (JSONException e) {
                        layout_no_store.setVisibility(View.VISIBLE);
                        if (isRefresh){
                            isRefresh=false;
                        }else if (isLoadMore){
                            isLoadMore=false;
                            mPage--;
                        }
                        e.printStackTrace();
                    }
                }
            }
*/
       /*     @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
                refreshListView.onRefreshComplete();
                showMsg("当前网络不可用，请检查网络");
                layout_no_store.setVisibility(View.VISIBLE);
                if (isRefresh){
                    isRefresh=false;
                }else if(isLoadMore){
                    isLoadMore=false;
                    mPage--;
                }

            }
        });
    }*/

    //店铺分类选择
    @Override
    public void initData() {
//        if (!NetworkUtils.isNetworkAvailable(this)) {
//            showMsg("请检查网络");
//        }
      /*  RequestParams params = new RequestParams();
        params.addBodyParameter("", "");

        loadData(HttpRequest.HttpMethod.POST, ApiDefine.STORE_CATRGORY, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                Log.e(TAG, "onSuccess response.result" +
                        response.result);

                try {
                    JSONObject jsonObject = new JSONObject(response.result);
                    String code = jsonObject.getString("code");
                    if (code.equalsIgnoreCase("100")) {

                        JSONArray list = jsonObject.getJSONArray("list");
                        data.clear();
                        for (int i = 0; i < list.length(); i++) {
                            ScreenStoreModel info = new ScreenStoreModel();
                            JSONObject temp = list.getJSONObject(i);
                            String tcId = temp.getString("tcId");
                            //Log.v(TAG, "-------------------tcid=" + tcId);
                            String tcName = temp.getString("tcName");

                            if (label != null && label.equals(tcName)) {
                                info.setIsSelect(true);
                            }
                            //String tcPic = temp.getString("tcPic");
                            info.setLabel(tcName);
                            info.setTcId(tcId);
                            data.add(info);
                        }
                        //                TODO 需换成真是字段名成
//                        mAdapter.setData(data);
                        mAdapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }


            @Override
            public void onFailure(HttpException e, String s) {
                //showMsg("当前网络不可用，请检查网络设置");

            }
        });

*/
    }

    //区域选择
    public void selectArea() {
     /*   //Intent intent = new Intent();
        String cityId = SPHelper.getCityId();
        RequestParams params = new RequestParams();
        params.addBodyParameter("type", "3");
        params.addBodyParameter("id", cityId);
        System.out.println("-----------cityID=" + cityId);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.FINDLOCATION_LIST, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                Log.e(TAG, "StoreListActivity respone.result:"
                        + response.result);
                try {
                    JSONObject jsonObject = new JSONObject(response.result);
                    String code = jsonObject.getString("code");
                    if (code.equalsIgnoreCase("100")) {
                        JSONArray result = jsonObject.getJSONArray("result");
                        areaData.clear();
                        for (int i = 0; i < result.length(); i++) {
                            ScreenStoreModel model = new ScreenStoreModel();
                            JSONObject temp = result.getJSONObject(i);
                            String id = temp.getString("id");
                            String name = temp.getString("name");
                            if (area != null && area.equals(name)) {
                                model.setIsSelect(true);
                            }
                            model.setAreaId(id);
                            model.setLabel(name);
                            areaData.add(model);
                        }
                        //                TODO 需换成真是字段名成
//                        mAdapter.setData(areaData);
                        mAdapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                //showMsg("当前网络不可用，请检查网络");
            }
        });*/
    }

    private boolean isLevelSelect = true;
    private boolean isTimeSelect = true;

    @Override
    public void onClick(View view) {
      /*  switch (view.getId()) {
            case R.id.layout_servicebag:
                tv_servicebag.setTextColor(getResources().getColor(R.color.bg_button_normal));
                tv_area.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_storelevel.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_time.setTextColor(getResources().getColor(R.color.textcolor_black));
                iv_servicebag.setImageResource(R.mipmap.top2);
                iv_area.setImageResource(R.mipmap.down);
                iv_storelevel.setImageResource(R.mipmap.down);
                iv_time.setImageResource(R.mipmap.down);
                //                TODO 需换成真是字段名成
//                mAdapter.setData(data);
                mPosition = 1;
                showPopUpWindow();
                showAndDismiss(view);
                initData();
                break;
            case R.id.layout_area:
                tv_servicebag.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_area.setTextColor(getResources().getColor(R.color.bg_button_normal));
                tv_storelevel.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_time.setTextColor(getResources().getColor(R.color.textcolor_black));
                iv_servicebag.setImageResource(R.mipmap.down);
                iv_area.setImageResource(R.mipmap.top2);
                iv_storelevel.setImageResource(R.mipmap.down);
                iv_time.setImageResource(R.mipmap.down);
                //                TODO 需换成真是字段名成
//                mAdapter.setData(areaData);
                mPosition = 2;
                showPopUpWindow();
                showAndDismiss(view);
                selectArea();
                break;
            case R.id.layout_storelevel:
                tv_servicebag.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_area.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_storelevel.setTextColor(getResources().getColor(R.color.bg_button_normal));
                tv_time.setTextColor(getResources().getColor(R.color.textcolor_black));
                iv_servicebag.setImageResource(R.mipmap.down);
                iv_area.setImageResource(R.mipmap.down);
                iv_storelevel.setImageResource(R.mipmap.top2);
                iv_time.setImageResource(R.mipmap.down);
                //                TODO 需换成真是字段名成
//                mAdapter.setData(storelvData);
                mPosition = 3;
                mTime = "";
                showPopUpWindow();
                showAndDismiss(view);
                break;
            case R.id.layout_time:
                tv_servicebag.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_area.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_storelevel.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_time.setTextColor(getResources().getColor(R.color.bg_button_normal));
                iv_servicebag.setImageResource(R.mipmap.down);
                iv_area.setImageResource(R.mipmap.down);
                iv_storelevel.setImageResource(R.mipmap.down);
                iv_time.setImageResource(R.mipmap.top2);
//                TODO 需换成真是字段名成
//                mAdapter.setData(timeData);
                mPosition = 4;
                mLevel = "";
                showPopUpWindow();
                showAndDismiss(view);
                break;
            default:
                break;
        }*/

    }

    /**
     * 显示popupwindow
     */
   /* public void showPopUpWindow() {
        //引入窗口布局文件
        View view = getLayoutInflater().inflate(R.layout.pop_storelist, null);
        //创建popupwindow对象
        popupWindow = new PopupWindow(view, ViewPager.LayoutParams.MATCH_PARENT,
                ViewPager.LayoutParams.WRAP_CONTENT, false);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //设置点击窗口外边窗口消失
        popupWindow.setOutsideTouchable(true);
        // 设置此参数获得焦点，否则无法点击
        popupWindow.setFocusable(true);
        listView = (ListView) view.findViewById(R.id.listview);
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

                switch (mPosition) {
                    case 1:
                        for (int j = 0; j < data.size(); j++) {
                            data.get(j).setIsSelect(false);
                        }
                        tcId = data.get(position).getTcId();
                        label = data.get(position).getLabel();
                        setTitle(label);
                        data.get(position).setIsSelect(true);
                        mAdapter.notifyDataSetChanged();
                        text = data.get(position).getLabel();
                        tv_servicebag.setTextColor(getResources().getColor(R.color.textcolor_black));
                        iv_servicebag.setImageResource(R.mipmap.down);
                        tv_servicebag.setText(text);
                        loadStoreData(tcId, areaID);
                        break;
                    case 2:
                        for (int j = 0; j < areaData.size(); j++) {
                            areaData.get(j).setIsSelect(false);
                        }
                        area = areaData.get(position).getLabel();
                        areaID = areaData.get(position).getAreaId();
                        Log.e(TAG, "---------areaID=" + areaID);
                        areaData.get(position).setIsSelect(true);
                        mAdapter.notifyDataSetChanged();
                        text = areaData.get(position).getLabel();
                        tv_area.setTextColor(getResources().getColor(R.color.textcolor_black));
                        iv_area.setImageResource(R.mipmap.down);
                        tv_area.setText(text);
                        loadStoreData(tcId, areaID);
                        break;
                    case 3:
                        if (storelvData.get(position).getLabel() == "从高到低") {
                            mLevel = "1";
                        } else if (storelvData.get(position).getLabel() == "从低到高") {
                            mLevel = "2";
                        }
                        for (int i = 0; i < storelvData.size(); i++) {
                            storelvData.get(i).setIsSelect(false);
                        }
                        Log.e("TAG", "mLevel:" + mLevel);
                        //level=storelvData.get(position).getLabel();
                        storelvData.get(position).setIsSelect(true);
                        mAdapter.notifyDataSetChanged();
                        text = storelvData.get(position).getLabel();
                        tv_storelevel.setTextColor(getResources().getColor(R.color.textcolor_black));
                        iv_storelevel.setImageResource(R.mipmap.down);
                        tv_storelevel.setText(text);
                        loadStoreData(tcId, areaID);
                        break;
                    case 4:
                        if (timeData.get(position).getLabel() == "新店开张") {
                            mTime = "1";
                        } else if (timeData.get(position).getLabel() == "精品老店") {
                            mTime = "2";
                        }
                        for (int i = 0; i < storelvData.size(); i++) {
                            timeData.get(i).setIsSelect(false);
                        }
                        timeData.get(position).setIsSelect(true);
                        mAdapter.notifyDataSetChanged();
                        text = timeData.get(position).getLabel();
                        tv_time.setTextColor(getResources().getColor(R.color.textcolor_black));
                        iv_time.setImageResource(R.mipmap.down);
                        tv_time.setText(text);
                        loadStoreData(tcId, areaID);
                        break;
                }
                popupWindow.dismiss();
            }
        });
    }*/

    /**
     * 显示和关闭popupwindow
     *
     * @param view
     */
    public void showAndDismiss(View view) {
        if (popupWindow.isShowing()) {
            // 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
            popupWindow.dismiss();

        } else {
            // 显示窗口
            popupWindow.showAsDropDown(view);

        }
    }
}
